const express = require('express');
const axios = require('axios');
const db = require('../db');
require('dotenv').config();

const router = express.Router();

// AI API配置
const AI_API_URL = process.env.AI_API_URL || 'https://4.0.wokaai.com/v1';
const AI_API_KEY = process.env.AI_API_TOKEN || 'sk-zMtcC2EFOaQyclovlYumnBJri4FZ5FjH5Jd5v3Jixdt2Knz1';

// 测试数据库连接
router.get('/test-db', async (req, res) => {
  try {
    const success = await db.testConnection();
    if (success) {
      res.json({ success: true, message: '数据库连接成功' });
    } else {
      res.status(500).json({ success: false, message: '数据库连接失败' });
    }
  } catch (error) {
    console.error('数据库连接失败:', error);
    res.status(500).json({ success: false, message: '数据库连接失败', error: error.message });
  }
});

// 获取可用的AI模型
router.get('/models', async (req, res) => {
  try {
    // 首先尝试从数据库获取模型配置
    let dbModels = [];
    try {
      dbModels = await db.query('SELECT * FROM model_configs WHERE is_active = TRUE');
    } catch (dbError) {
      console.warn('从数据库获取模型失败:', dbError.message);
      // 数据库查询失败时继续执行，使用默认模型
    }
    
    if (dbModels && dbModels.length > 0) {
      return res.json({
        success: true,
        data: dbModels.map(model => ({
          id: model.model_id,
          name: model.display_name,
          hasDeepThinking: model.has_deep_thinking === 1
        }))
      });
    }
    
    // 如果数据库中没有模型配置，则使用默认模型或从API获取
    try {
      const response = await axios.get(`${AI_API_URL}/models`, {
        headers: {
          'Authorization': `Bearer ${AI_API_KEY}`
        }
      });
      
      res.json({
        success: true,
        data: response.data.data.map(model => ({
          id: model.id,
          name: model.id.split('/').pop(),
          hasDeepThinking: model.id.includes('deepseek')
        }))
      });
    } catch (apiError) {
      console.error('从API获取模型列表失败:', apiError.message);
      
      // 如果API请求也失败，返回默认模型列表
      res.json({
        success: true,
        data: [
          { id: 'gpt-3.5-turbo', name: 'GPT-3.5', hasDeepThinking: false },
          { id: 'gpt-4', name: 'GPT-4', hasDeepThinking: false },
          { id: 'deepseek-chat', name: 'DeepSeek', hasDeepThinking: true }
        ]
      });
    }
  } catch (error) {
    console.error('获取模型列表失败:', error.message);
    res.status(500).json({ 
      success: false, 
      message: '获取模型列表失败', 
      error: error.message 
    });
  }
});

// 发送聊天请求
router.post('/chat', async (req, res) => {
  try {
    const { model, messages, options, userId = 'anonymous' } = req.body;
    
    if (!model || !messages || !Array.isArray(messages) || messages.length === 0) {
      return res.status(400).json({ 
        success: false, 
        message: '缺少必要参数或参数格式不正确' 
      });
    }
    
    // 调用AI API
    const response = await axios.post(`${AI_API_URL}/chat/completions`, {
      model,
      messages,
      ...options
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${AI_API_KEY}`
      }
    });
    
    // 获取用户消息和AI回复
    const userMessage = messages[messages.length - 1].content;
    const aiResponse = response.data.choices[0].message.content;
    
    // 获取tokens信息
    const promptTokens = response.data.usage?.prompt_tokens || 0;
    const completionTokens = response.data.usage?.completion_tokens || 0;
    const totalTokens = response.data.usage?.total_tokens || promptTokens + completionTokens;
    
    // 保存对话记录到数据库
    try {
      await db.query(
        'INSERT INTO chat_history (user_id, model, user_message, ai_response, created_at) VALUES (?, ?, ?, ?, NOW())',
        [userId, model, userMessage, aiResponse]
      );
    } catch (dbError) {
      console.warn('保存对话记录到数据库失败:', dbError.message);
      // 数据库操作失败时继续执行，不影响API响应
    }
    
    res.json({
      success: true,
      data: {
        content: aiResponse,
        model: model,
        tokens: totalTokens,
        promptTokens: promptTokens,
        completionTokens: completionTokens
      }
    });
  } catch (error) {
    console.error('聊天请求失败:', error.response?.data || error.message);
    res.status(500).json({ 
      success: false, 
      message: '聊天请求失败', 
      error: error.response?.data || error.message 
    });
  }
});

// 获取用户的聊天历史
router.get('/history/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { limit = 50, offset = 0 } = req.query;
    
    const rows = await db.query(
      'SELECT * FROM chat_history WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
      [userId, parseInt(limit), parseInt(offset)]
    );
    
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('获取聊天历史失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取聊天历史失败', 
      error: error.message 
    });
  }
});

// 创建聊天会话
router.post('/sessions', async (req, res) => {
  try {
    const { userId, model, title } = req.body;
    
    if (!userId || !model) {
      return res.status(400).json({ 
        success: false, 
        message: '缺少必要参数' 
      });
    }
    
    const sessionId = require('crypto').randomUUID();
    
    await db.query(
      'INSERT INTO chat_sessions (id, user_id, model, title) VALUES (?, ?, ?, ?)',
      [sessionId, userId, model, title || '新对话']
    );
    
    res.json({ 
      success: true, 
      data: { 
        sessionId,
        userId,
        model,
        title: title || '新对话',
        createdAt: new Date()
      } 
    });
  } catch (error) {
    console.error('创建聊天会话失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '创建聊天会话失败', 
      error: error.message 
    });
  }
});

// 获取用户的聊天会话列表
router.get('/sessions/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { limit = 20, offset = 0 } = req.query;
    
    const rows = await db.query(
      'SELECT * FROM chat_sessions WHERE user_id = ? ORDER BY updated_at DESC LIMIT ? OFFSET ?',
      [userId, parseInt(limit), parseInt(offset)]
    );
    
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('获取聊天会话列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取聊天会话列表失败', 
      error: error.message 
    });
  }
});

// 获取会话的消息列表
router.get('/sessions/:sessionId/messages', async (req, res) => {
  try {
    const { sessionId } = req.params;
    const { limit = 100, offset = 0 } = req.query;
    
    const rows = await db.query(
      'SELECT * FROM chat_messages WHERE session_id = ? ORDER BY created_at ASC LIMIT ? OFFSET ?',
      [sessionId, parseInt(limit), parseInt(offset)]
    );
    
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('获取会话消息列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取会话消息列表失败', 
      error: error.message 
    });
  }
});

// 添加消息到会话
router.post('/sessions/:sessionId/messages', async (req, res) => {
  try {
    const { sessionId } = req.params;
    const { role, content } = req.body;
    
    if (!role || !content) {
      return res.status(400).json({ 
        success: false, 
        message: '缺少必要参数' 
      });
    }
    
    await db.query(
      'INSERT INTO chat_messages (session_id, role, content) VALUES (?, ?, ?)',
      [sessionId, role, content]
    );
    
    // 更新会话的更新时间
    await db.query(
      'UPDATE chat_sessions SET updated_at = NOW() WHERE id = ?',
      [sessionId]
    );
    
    res.json({ 
      success: true, 
      message: '消息添加成功' 
    });
  } catch (error) {
    console.error('添加消息失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '添加消息失败', 
      error: error.message 
    });
  }
});

module.exports = router; 